﻿
using Microsoft.AspNetCore.Mvc.Versioning;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using static System.String;

namespace BJoin.DemoProject.RW.Webapi
{
    public class ApiVersionErrorResponseProvider: DefaultErrorResponseProvider, IErrorResponseProvider
    {
        /// <summary>
        /// Creates the default error content using the given context.
        /// </summary>
        /// <param name="context">The <see cref="ErrorResponseContext">error context</see> used to create the error content.</param>
        /// <returns>An <see cref="object"/> representing the error content.</returns>
        protected override object CreateErrorContent(ErrorResponseContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            var message = context.Message;
            if (!string.IsNullOrEmpty(message))
            {
                var reg = new Regex("URI '.*?'", RegexOptions.IgnoreCase);
                message = reg.Replace(message, $"URI '{context.Request.Path.ToString()}'");
            }

            //return new
            //{
            //    Error = new
            //    {
            //        Code = NullIfEmpty(context.ErrorCode),
            //        Message = NullIfEmpty(context.Message),
            //        InnerError = NewInnerError(context, c => new { Message = c.MessageDetail }),
            //    },
            //};
            return NullIfEmpty(message) ?? ((HttpStatusCode)context.StatusCode).ToString();
        }

        private static string NullIfEmpty(string value) => IsNullOrEmpty(value) ? null : value;
    }
}
